package model

import (
	"fmt"
	"gorm.io/gorm"
	"next-vue-backend/utils/errmsg"
)

type Idea struct {
	gorm.Model
	Title string `gorm:"type:varchar(100); not null" json:"title"`
	Content string `gorm:"type:longtext" json:"content"`
	Img string `gorm:"type:varchar(100)" json:"img"`
}

// CreateIdea 创建想法
func CreateIdea (data *Idea) int {
	err := db.Create(&data).Error
	fmt.Println(err)
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// GetIdeaList 查询想法列表
func GetIdeaList (pageSize int, pageNum int) ([]Idea, int, int64) {
	var ideaList []Idea
	var total int64
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&ideaList).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return  nil, errmsg.ERROR, 0
	}
	return  ideaList, errmsg.SSUCCESS, total
}

// EditIdea 编辑想法
func EditIdea (id int, data *Idea) int {
	var idea Idea
	var maps = make(map[string] interface{})
	maps["title"] = data.Title
	maps["content"] = data.Content
	maps["img"] = data.Img
	err = db.Model(&idea).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// DeleteIdea 删除想法
func DeleteIdea(id int) int {
	var idea Idea
	err = db.Where("id = ? ", id).Delete(&idea).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}